package com.cjx.leetcode.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cjx
 * @Description E216.组合总和Ⅲ
 * @date 2024/3/31 9:01
 **/
public class E216 {

    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k,n,1);
        return result;
    }
    public void backtracking(int k , int n , int startIndex){
        // 减枝
        if (sum > n) {
            return;
        }
        if (path.size() == k){
            if (sum == n){
            result.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1 ; i++) {
                sum  += i;
                path.add(i);
            backtracking(k,n,i + 1);
            sum -= i;
            path.remove(path.size() - 1);
        }
    }
}
